package org.example.ams.controller.system;

import org.example.ams.entity.system.SysUser;
import org.example.ams.log.Log;
import org.example.ams.service.system.ILoginService;
import org.example.ams.util.SystemUtils;
import org.example.ams.vo.LoginUser;
import org.example.common.api.CommonResult;
import org.example.security.util.CaptchaUtils;
import org.example.security.util.LoginUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.Set;

@RestController
public class LoginController {
    @Autowired
    private ILoginService loginService;
    @Autowired
    private SystemUtils systemUtils;

    /**
     * 登录接口
     */
    @Log(value = "用户登录")
    @PostMapping("/login")
    public CommonResult<String> login(@RequestBody LoginUser user) {
        if (user == null) {
            return CommonResult.validateFailed();
        }
        return loginService.login(user);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public CommonResult register(@RequestBody SysUser sysUser) {
        // TODO 用户注册
        return CommonResult.success(null);
    }

    /**
     * 获取登录用户详细信息
     */
    @GetMapping("/userinfo")
    public CommonResult<SysUser> getLoginUserInfo() {
        UserDetails userDetails = LoginUtils.currentLoginUser();
        SysUser sysUser = systemUtils.loginUser();
        sysUser.setPassword("");
        Set<String> permissions = new HashSet<>();
        for (GrantedAuthority authority : userDetails.getAuthorities()) {
            permissions.add(authority.getAuthority());
        }
        sysUser.setPermissions(permissions);
        return CommonResult.success(sysUser,null);
    }

    /**
     * 获取验证码接口
     */
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response){
        String s = CaptchaUtils.drawAlgExpCaptcha(response);
        // TODO 保存验证码结果
    }
}
